﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ext.Net;

public partial class SYS_POPEDOM_User_Manage : BasePage
{
    private static string clickNodeId = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BuildTreeRoot();
            AddTabForMaster();
        }
    }

    private void AddTabForMaster()
    {
        string Url = G_Url_allstring + "/SYS_POPEDOM/User_Create.aspx";
        String tabid = Request.QueryString["tabid"];
        extBtn_Edit.Listeners.Click.Handler = "popfortab(GridPanel1,'" + Url + "','ObjId','USER_ID',0,'dept_id='+#{TreePanel1}.getSelectionModel().getSelectedNode().id,'" + tabid + "','操作员编辑',2)";
        GridPanel1.Listeners.RowDblClick.Handler = "popfortab(GridPanel1,'" + Url + "','ObjId','USER_ID',rowIndex,'dept_id='+#{TreePanel1}.getSelectionModel().getSelectedNode().id,'" + tabid + "','操作员编辑',3)";

    }

    protected void OnStoreRefreshData(object sender, StoreRefreshDataEventArgs e)
    {
        BindGrid("NodeClick");
    }

    //单击树节点


    [DirectMethod]
    public void NodeClick(string NodeId)
    {
        clickNodeId = NodeId;
        GridPanel1.Reload();
    }

    protected void extBtn_Find_Click(object sender, DirectEventArgs e)
    {
        BindGrid("Find_Click");
    }

    protected void OnExtBtnAddClick(object sender, DirectEventArgs e)
    {
        string dept_id = e.ExtraParams["deptid"];
        if (dept_id.IndexOf(BS_LoginDeptId.Trim()) > -1)
        {
            string Url = G_Url_allstring + "/SYS_POPEDOM/User_Create.aspx";
            String tabid = Request.QueryString["tabid"];
            X.AddScript("popfortab(GridPanel1,'" + Url + "','ObjId','Add',0,'dept_id=" + dept_id + "','" + tabid + "','操作员增加',1)");
        }
        else
        {
            X.Msg.Alert("系统提示","您没有创建所选部门操作员的权限").Show();
        }


    }

    //加载列表
    private void BindGrid(string searchType)
    {
        DataTable GridData = null;
        if (searchType == "Find_Click")
        {

            string sql = string.Format(@"with cte as
(
    select * from( select a.*,b.DEPT_NAME PARENT_NAME from SYS_DEPT a LEFT join SYS_DEPT b on b.DEPT_ID = a.PARENT_ID ) t
    where rtrim(ltrim(DEPT_ID))='{0}' 
    union all
    select d.*,c.DEPT_NAME PARENT_NAME from cte c inner join SYS_DEPT d
    on c.DEPT_ID = d.PARENT_ID
)
select n.*,m.DEPT_NAME,dr.ROLE_ID,sr.ROLE_NAME,sor.USER_ID from cte m
inner join SYS_USER n on n.DEPT_ID = m.DEPT_ID 
inner join SYS_DEPT_ROLES dr on dr.DEPT_ID=n.DEPT_ID
inner join dbo.SYS_ROLES sr on sr.ROLE_ID =dr.ROLE_ID
inner join sys_operator_role sor on sor.MASTER_ID=dr.MASTER_ID and n.USER_ID=sor.USER_ID
where n.del_flag=0 and (USER_NAME like '%{1}%' OR n.USER_ID LIKE '%{1}%' OR USER_PYM LIKE '%{1}%') or sr.ROLE_NAME like '%{1}%'
order by display_order
", clickNodeId.Trim(), exttxtf_user_name.Text.Trim());

            GridData = CommonLib.BLL.BS_DATASET_SQL.SqlGetTable(sql);
        }
        else
        {
            GridData = CommonLib.BLL.SYS_USER.GetList(GetQryString(), "display_order").Tables[0];
        }
        this.Store1.DataSource = GridData;
        this.Store1.DataBind();
    }
    private string GetQryString()
    {
        string result = "del_flag=0 and dept_id like '" + clickNodeId + "%' ";
        if (exttxtf_user_name.Text != "")
            result += string.Format(" and (USER_NAME like '%{0}%' OR USER_ID LIKE '%{0}%' OR USER_PYM LIKE '%{0}%')", exttxtf_user_name.Text);
        return result;
    }

    //构建部门树根节点
    private void BuildTreeRoot()
    {
        DataTable tmpDt = CommonLib.BLL.SYS_DEPT.GetListSub(" dept_id='00' and  del_flag =0 ", "dept_no").Tables[0];
        if (tmpDt.Rows.Count == 1)
        {
            Ext.Net.AsyncTreeNode root = new Ext.Net.AsyncTreeNode();
            root.Text = tmpDt.Rows[0]["dept_name"].ToString();
            root.NodeID = tmpDt.Rows[0]["dept_id"].ToString();
            root.Expanded = true;
            root.IconCls = "no-icon";
            if (tmpDt.Rows[0]["leaf"].ToString() == "0")
                root.Leaf = true;
            root.Draggable = true;
            this.TreePanel1.Root.Add(root);
        }
    }


    //加载下属节点
    [DirectMethod]
    public string NodeLoad(string nodeID)
    {
        Ext.Net.TreeNodeCollection nodes = new Ext.Net.TreeNodeCollection();
        if (!string.IsNullOrEmpty(nodeID))
        {
            DataTable TreeData = CommonLib.BLL.SYS_DEPT.GetListSub(" del_flag =0 and ltrim(rtrim(dept_id)) like '" + nodeID.Trim() + "__' ", "dept_no").Tables[0];
            for (int i = 0; i < TreeData.Rows.Count; i++)
            {
                AsyncTreeNode asyncNode = new AsyncTreeNode();
                asyncNode.Text = TreeData.Rows[i]["dept_name"].ToString();
                asyncNode.NodeID = TreeData.Rows[i]["dept_id"].ToString();
                asyncNode.IconCls = "no-icon";
                if (TreeData.Rows[i]["leaf"].ToString() == "0")
                    asyncNode.Leaf = true;
                nodes.Add(asyncNode);
            }
        }
        clickNodeId = nodeID;
        BindGrid("NodeClick");
        return nodes.ToJson();
    }


    /// <summary>
    /// 删除操作员
    /// </summary>
    protected void DelUser(object sender, DirectEventArgs e)
    {
        int nCount = 0;
        RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
        nCount = sm.SelectedRows.Count;
        if (nCount == 0)
        {
            X.Msg.Alert("系统提示", "请先选择要删除的记录！").Show();
            return;
        }
        X.Msg.Confirm("系统提示", "是否删除选中行?", new MessageBoxButtonsConfig
        {
            Yes = new MessageBoxButtonConfig
            {
                Handler = "Ext.net.DirectMethods.DoDelMenu(#{TreePanel1}.getSelectionModel().getSelectedNode().id);",
                Text = "是"
            },
            No = new MessageBoxButtonConfig
            {

                Text = "否"
            }
        }).Show();

    }

    [DirectMethod]
    public void DoDelMenu(string dept_id)
    {
        if (dept_id.IndexOf(BS_LoginDeptId.Trim()) == -1)
        {
            X.Msg.Alert("系统提示", "您没有删除所选部门操作员的权限").Show();
            return;
        }

        RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
        string recordIDs = "";
        foreach (SelectedRow row in sm.SelectedRows)
        {
            recordIDs = recordIDs + row.RecordID.Trim() + ";";
        }
        try
        {
            if (CommonLib.BLL.SYS_USER.DeleteTrans(recordIDs) == 0)
            {
                X.Msg.Alert("系统提示", "删除记录失败！").Show();
                return;
            }
            else
            {
                if (clickNodeId != "")
                    BindGrid("NodeClick");
            }
        }
        catch
        {
            X.Msg.Alert("系统提示", "删除记录失败！").Show();
            return;
        }
    }

}
